package com.rg.filter;

import com.rg.model.UserModel;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class loginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //获取用户请求资源
        String url = request.getServletPath().toString();
        //获取用户请求资源的名称,路径最后一个/后的名称
        String urlName = url.substring(url.lastIndexOf("/")+1);
        //设置放行页面（不登录也可以访问的页面）
        if(("login.jsp".equals(urlName)||"register.jsp".equals(urlName)||"UserLoginServlet".equals(urlName)||"UserRegisterServlet".equals(urlName)||"checkUsernameServlet".equals(urlName)||urlName.endsWith(".css"))||urlName.endsWith(".js")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //通过session记录用户信息
            HttpSession session = request.getSession();
            UserModel user = (UserModel)session.getAttribute("user");
            //判断在session中是否存储了该用户的信息
            if(user==null){
                request.setAttribute("notLoginInfo","<label style='color:red'>您尚未登录！请登录使用本网站！</label>");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }else {
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
